package com.promise.jokerdream.repository

import com.promise.jokerdream.network.HttpApiConstants
import com.promise.jokerdream.response.parser.SimpleXmlParser
import com.promise.jokerdream.response.phone.SimpleXmlResponse
import com.promise.jokerdream.response.phone.PenguinShareXmlResponse
import com.promise.jokerdream.response.phone.WulinXmlResponse
import com.promise.jokerdream.response.phone.XiaLvXmlResponse
import com.promise.jokerdream.response.phone.FactionFriendXmlResponse
import com.promise.jokerdream.response.phone.FriendListXmlResponse
import com.promise.jokerdream.response.phone.FightFactionMineXmlResponse
import com.promise.jokerdream.response.phone.FightKnightDreamXmlResponse
import com.promise.jokerdream.response.phone.FightTowerXmlResponse
import com.promise.jokerdream.response.phone.CurrencyExchangeXmlResponse
import com.promise.jokerdream.response.phone.FightKnightArenaXmlResponse
import com.promise.jokerdream.response.phone.LatestActXmlResponse
import com.promise.jokerdream.response.phone.QueryAssistantXmlResponse
import com.promise.jokerdream.response.phone.FightProcessXmlResponse
import com.promise.jokerdream.utils.UrlUtils

/**
 * 手机端游戏API接口
 * 定义所有手机端XML响应的API调用方法
 */
class PhoneGameApi {
    
    private val repository = PhoneGameRepository.getInstance()
    
    // ==================== 侠侣相关API ====================
    
    /**
     * 查询侠侣信息
     * @return 侠侣响应数据
     */
    suspend fun queryXiaLvData(): Result<XiaLvXmlResponse> {
        val url = UrlUtils.buildUrl(HttpApiConstants.PhoneUrls.xialv, emptyMap())
        return repository.get(url).fold(
            onSuccess = { responseBody ->
                repository.parseXiaLvResponse(responseBody)
            },
            onFailure = { exception ->
                Result.failure(exception)
            }
        )
    }
    
    /**
     * 根据URL查询XML数据
     * @param url 请求URL
     * @return 解析后的XML数据
     */
    suspend fun queryXmlData(url: String): Result<SimpleXmlResponse> {
        return repository.get(url).fold(
            onSuccess = { responseBody ->
                repository.parseXmlResponse(url, responseBody).fold(
                    onSuccess = { result ->
                        if (result is SimpleXmlResponse) {
                            Result.success(result)
                        } else {
                            Result.failure(Exception("解析结果类型错误"))
                        }
                    },
                    onFailure = { exception ->
                        Result.failure(exception)
                    }
                )
            },
            onFailure = { exception ->
                Result.failure(exception)
            }
        )
    }
    
    /**
     * 好友挑战
     * @param url 挑战URL
     * @return 挑战结果响应数据
     */
    suspend fun fightFriend(url: String): Result<SimpleXmlResponse> {
        return repository.get(url).fold(
            onSuccess = { responseBody ->
                repository.parseFightFriendResponse(responseBody)
            },
            onFailure = { exception ->
                Result.failure(exception)
            }
        )
    }
    
    /**
     * 查询帮友信息
     * @param page 页码，默认为1
     * @return 帮友响应数据
     */
    suspend fun queryFactionFriendData(page: Int = 1): Result<FactionFriendXmlResponse> {
        val url = UrlUtils.buildUrl(HttpApiConstants.PhoneUrls.factionFriend, mapOf("page" to page.toString()))
        return repository.get(url).fold(
            onSuccess = { responseBody ->
                repository.parseFactionFriendResponse(responseBody)
            },
            onFailure = { exception ->
                Result.failure(exception)
            }
        )
    }
    
    /**
     * 查询好友列表信息
     * @param page 页码，默认为1
     * @return 好友列表响应数据
     */
    suspend fun queryFriendListData(page: Int = 1): Result<FriendListXmlResponse> {
        val url = UrlUtils.buildUrl(HttpApiConstants.PhoneUrls.friendList, mapOf("page" to page.toString()))
        return repository.get(url).fold(
            onSuccess = { responseBody ->
                repository.parseFriendListResponse(responseBody)
            },
            onFailure = { exception ->
                Result.failure(exception)
            }
        )
    }
    
    // ==================== 竞技场相关API ====================
    
    /**
     * 竞技场挑战
     * @return 挑战结果响应数据
     */
    suspend fun arenaChallenge(): Result<SimpleXmlResponse> {
        val url = UrlUtils.buildUrl(HttpApiConstants.PhoneUrls.challengeArena, emptyMap())
        return repository.get(url).fold(
            onSuccess = { responseBody ->
                repository.parseArenaChallengeResponse(responseBody)
            },
            onFailure = { exception ->
                Result.failure(exception)
            }
        )
    }
    
    // ==================== 矿洞相关API ====================
    
    /**
     * 挑战矿洞
     * @return 矿洞挑战响应数据
     */
    suspend fun fightFactionMine(): Result<FightFactionMineXmlResponse> {
        val url = UrlUtils.buildUrl(HttpApiConstants.PhoneUrls.factionMine, emptyMap())
        return repository.get(url).fold(
            onSuccess = { responseBody ->
                repository.parseFightFactionMineResponse(responseBody)
            },
            onFailure = { exception ->
                Result.failure(exception)
            }
        )
    }
    
    // ==================== 斗神塔相关API ====================
    
    /**
     * 查询斗神塔信息
     * @return 斗神塔响应数据
     */
    suspend fun queryTowerFightData(): Result<FightTowerXmlResponse> {
        val url = UrlUtils.buildUrl(HttpApiConstants.PhoneUrls.towerFight, emptyMap())
        return repository.get(url).fold(
            onSuccess = { responseBody ->
                repository.parseFightTowerResponse(responseBody)
            },
            onFailure = { exception ->
                Result.failure(exception)
            }
        )
    }
    
    // ==================== 江湖长梦相关API ====================
    
    /**
     * 查询江湖长梦XML数据
     * @return 江湖长梦XML响应数据
     */
    suspend fun queryKnightDreamXmlData(copyId: Int): Result<FightKnightDreamXmlResponse> {
        val url = UrlUtils.buildUrl(HttpApiConstants.PhoneUrls.fightKnightDream, mapOf(
            "ins_id" to copyId.toString()
        ))
        return repository.get(url).fold(
            onSuccess = { responseBody ->
                repository.parseFightKnightDreamResponse(responseBody)
            },
            onFailure = { exception ->
                Result.failure(exception)
            }
        )
    }
    
    /**
     * 执行斗神塔操作（开始挑战、挑战下一层、结束挑战、自动挑战、复活）
     * @param actionUrl 操作URL
     * @return 执行后的斗神塔响应数据
     */
    suspend fun executeTowerAction(actionUrl: String): Result<FightTowerXmlResponse> {
        return repository.get(actionUrl).fold(
            onSuccess = { responseBody ->
                repository.parseFightTowerResponse(responseBody)
            },
            onFailure = { exception ->
                Result.failure(exception)
            }
        )
    }
    
    // ==================== 其他手机端API ====================
    
    /**
     * 武林报名
     * @return 武林大会响应数据
     */
    suspend fun signWulin(): Result<WulinXmlResponse> {
        val url = UrlUtils.buildUrl(HttpApiConstants.PhoneUrls.fastSignWulin, emptyMap())
        return repository.get(url).fold(
            onSuccess = { responseBody ->
                repository.parseWulinResponse(responseBody)
            },
            onFailure = { exception ->
                Result.failure(exception)
            }
        )
    }
    
    /**
     * 一键分享游戏
     * @return 企鹅分享响应数据
     */
    suspend fun shareGame(): Result<PenguinShareXmlResponse> {
        val url = UrlUtils.buildUrl(HttpApiConstants.PhoneUrls.fastShareGame, emptyMap())
        return repository.get(url).fold(
            onSuccess = { responseBody ->
                repository.parsePenguinShareResponse(responseBody)
            },
            onFailure = { exception ->
                Result.failure(exception)
            }
        )
    }
    
    // ==================== 货币兑换相关API ====================
    
    /**
     * 货币兑换（鹅币兑换斗豆）
     * @param uin 用户ID
     * @param paynum 兑换数量（鹅币数量）
     * @return 货币兑换响应数据
     */
    suspend fun currencyExchange(uin: String, paynum: Int): Result<CurrencyExchangeXmlResponse> {
        val url = UrlUtils.buildUrl(HttpApiConstants.PhoneUrls.currencyExchange, mapOf(
            "zapp_uin" to uin,
            "paynum" to paynum.toString()
        ))
        
        // 构建Referer头，包含动态的zapp_uin和paytype参数
        val refererUrl = UrlUtils.buildUrl(HttpApiConstants.PhoneUrls.currencyExchangeReferer, mapOf(
            "zapp_uin" to uin,
            "paytype" to "8"
        ))
        
        val headers = mapOf(
            "Referer" to refererUrl
        )
        
        return repository.get(url, headers).fold(
            onSuccess = { responseBody ->
                repository.parseCurrencyExchangeResponse(responseBody)
            },
            onFailure = { exception ->
                Result.failure(exception)
            }
        )
    }
    
    // ==================== 侠士论剑相关API ====================
    
    /**
     * 侠士论剑挑战
     * @return 侠士论剑挑战响应数据
     */
    suspend fun fightKnightArena(): Result<FightKnightArenaXmlResponse> {
        val url = UrlUtils.buildUrl(HttpApiConstants.PhoneUrls.fightKnightArena, emptyMap())
        return repository.get(url).fold(
            onSuccess = { responseBody ->
                repository.parseFightKnightArenaResponse(responseBody)
            },
            onFailure = { exception ->
                Result.failure(exception)
            }
        )
    }
    
    // ==================== 乐斗助手相关API ====================
    
    /**
     * 查询乐斗助手设置
     */
    suspend fun queryAssistant(): Result<QueryAssistantXmlResponse> {
        val url = HttpApiConstants.PhoneUrls.assistant
        return repository.get(url).fold(
            onSuccess = { responseBody ->
                repository.parseAssistantResponse(responseBody)
            },
            onFailure = { exception ->
                Result.failure(exception)
            }
        )
    }
    
    /**
     * 访问助手设置链接
     */
    suspend fun accessAssistantLink(url: String): Result<QueryAssistantXmlResponse> {
        return repository.get(url).fold(
            onSuccess = { responseBody ->
                repository.parseAssistantResponse(responseBody)
            },
            onFailure = { exception ->
                Result.failure(exception)
            }
        )
    }
    
    /**
     * 查询首页活动信息
     * @return 最新活动响应数据
     */
    suspend fun queryLatestActData(): Result<LatestActXmlResponse> {
        val url = HttpApiConstants.PhoneUrls.home
        return repository.get(url).fold(
            onSuccess = { responseBody ->
                repository.parseLatestActResponse(responseBody)
            },
            onFailure = { exception ->
                Result.failure(exception)
            }
        )
    }
    
    /**
     * 查询战斗过程（单页）
     * @param url 战斗过程URL
     * @return 战斗过程响应数据
     */
    suspend fun queryFightProcess(url: String): Result<FightProcessXmlResponse> {
        return repository.get(url).fold(
            onSuccess = { responseBody ->
                repository.parseFightProcessResponse(responseBody)
            },
            onFailure = { exception ->
                Result.failure(exception)
            }
        )
    }
    
    companion object {
        @Volatile
        private var INSTANCE: PhoneGameApi? = null
        
        /**
         * 获取PhoneGameApi单例
         */
        fun getInstance(): PhoneGameApi {
            return INSTANCE ?: synchronized(this) {
                INSTANCE ?: PhoneGameApi().also { INSTANCE = it }
            }
        }
    }
}
